<?php

class cv_controller extends app_controller {
  /**
   * Action
   */
  function index() {
    if ($this->args && $this->args[0]) {
      $this->data = $cv = $this->args[0];

      if (/*strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') === FALSE
        &&*/ $cv->publicity == 'protected' && !$this->auth()) {
        goto('/pw');
      }

      $this->title = 'Lebenslauf';
      if (isset($cv->vorname) && isset($cv->nachname)) {
        $this->page_title = $cv->vorname . ' ' . $cv->nachname;
      }
      else {
        $this->page_title = $cv->url;
      }
      $_SESSION['destination'] = '/' . $cv->url;
    }
    else {
      $cv_generator = load('cv');
      $this->data = $cv_generator->read('cv8');
      
      $this->title = 'Ihr Online-Lebenslauf';

      $this->data->_has_many['ausbildung']['title'] = 'Merkmale';
      $this->data->_has_many['beruf']['title'] = 'Geplante Erweiterungen';

      $_SESSION['destination'] = '/';
    }
    $this->_styling();
    
    $this->data->has_many('ausbildung');
    $this->data->has_many('beruf');
    
    $this->referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
  }
  
  /**
   * Action
   */
  function pw_auth() {
    global $config;
    if ($this->args && $this->args[0]) {
      $this->data = $cv = $this->args[0];
      if ($this->auth()) {
        goto('/');
      }
    }
    else {
      goto('http://' . $config['mainhost'] . '/');
    }
    $this->_styling();

    if ($_POST) {
      if (isset($_POST['password']) && $_POST['password'] == $cv->prot_passwd) {
        $_SESSION['auth'][$cv->url] = TRUE;
        goto('/');
      }
      else {
        $_SESSION['message'] = 'Die Anmeldung schlug fehl. Bitte probieren Sie es erneut oder wenden Sie sich an den <a href="/kontakt">Autor des CV</a>, um ein neues Kennwort zu erhalten.';
      }
    }
    else {
      $descr = split("\n", wordwrap($cv->zusammenfassung, 200));
      $this->page_description = $descr[0];
    }
  }

  /**
   * Action
   */
  function pw_unauth() {
    global $config; 
    
    if ($this->args && $this->args[0]) {
      $cv = $this->args[0];
      unset($_SESSION['auth'][$cv->url]);
      if ($this->auth()) {
        goto('/');
      }
    }
    goto('http://' . $config['mainhost'] . '/');
  }

  /**
   * Action
   */
  function save() {
    $cv_generator = load('cv');

    error_log("SAVE.cv " . serialize($_POST));

    if (isset($_SESSION['user']) && $_SESSION['user']->url) {
      if ($this->data = $cv_generator->read($_SESSION['user']->url)) {
        $prev_url = $this->data->url;
        $this->data->save($_POST);
        if (isset($_POST['url'])) {
          rename('files/' . $prev_url, 'files/' . $_POST['url']);
          $_SESSION['user'] = $cv_generator->read($_POST['url']);
        }
      }
    }
    else {
      $_SESSION['message'] = 'Bitte melden Sie sich an, damit Ihre Änderungen gespeichert werden.';
    }
        
    $this->rendered = TRUE;
    $this->layout = FALSE;
    return nl2br(join(' ', $_POST));
  }
  
  /**
   * Action
   */
  function contact() {
    $this->title = 'Kontaktaufnahme';
    if ($this->args && $this->args[0]) {
      $this->data = $cv = $this->args[0];
      $this->page_title = 'Kontakt zu ' . $cv->vorname . ' ' . $cv->nachname;
    }
    else {
      $cv_generator = load('cv');
      $this->data = $cv_generator->read('cv8');
       $this->page_title = 'Kontakt zum CV Aid';
    }
    $this->_styling();
    
    if ($_POST) {
      $calc = $_SESSION['calc'];
      $chk = intval($_POST['chk']);
      // echo  'Aufgabe: ' . $calc['a'] . $op[$calc['n']] . $calc['b'] . ' = ' . $chk . "\n";
      // var_dump($_POST, $text);
      unset($_SESSION['message']);
      switch ($calc['n']) {
        case 0:
          if ($chk != $calc['a'] + $calc['b']) {
            $_SESSION['message'] = 'Bitte lösen Sie die Rechenaufgabe'; 
          }
          break;
          
        case 1:
          if ($chk != $calc['a'] - $calc['b']) {
            $_SESSION['message'] = 'Bitte lösen Sie die Rechenaufgabe'; 
          }
          break;
        
        case 2:
          if ($chk != $calc['a'] * $calc['b']) {
            $_SESSION['message'] = 'Bitte lösen Sie die Rechenaufgabe'; 
          }
          break;
      }
      
      if (!isset($_SESSION['message'])) {
        $text = nl2br($_POST['text']);
        send_mail($$this->data->email, '[cv8.me] Kontaktanfrage', "Hallo,

Sie haben folgende Kontaktanfrage erhalten:
----
{$text}
----

Viel Erfolg mit Ihrem Online-Lebenslauf!
Dr. Olav Schettler");

        $_SESSION['message'] = 'Vielen Dank. Ihre Nachricht wurde weitergeleitet.';
        goto('/');
      }
    }

    // prep form
    $op = array('plus', 'minus', 'mal');
    $a = rand(1, 10);
    $b = rand(1, 10);

    // make sure minus yields a positive result
    if ($a > $b) {
      $calc['a'] = $a;
      $calc['b'] = $b;
    }
    else {
      $calc['a'] = $b;
      $calc['b'] = $a;
    }
    $calc['n'] = rand(0, 2);
    $this->calc = $calc + array('op' => $op[$calc['n']]);

    $this->text = isset($_POST['text']) ? $_POST['text'] : '';
    $_SESSION['calc'] = $calc;
  }
  
  /**
   * Action
   */
  function login() {
    global $config; 
    
    global $DEBUG;
    $DEBUG = 9;
    $cv_generator = load('cv');
    if ($_POST) {
      $_SESSION['user'] = $cv_generator->one(array(
        'where' => 'email = %s AND password = PASSWORD(%s)', 
        'args' => array($_POST['email'], $_POST['password'])));
      unset($_SESSION['auth']);
      $msg = 'Willkommen zurück.';
    }
    else
    if (count($this->path) > 2) {
      $_SESSION['user'] = $cv_generator->one(array(
        'where' => 'code = %s', 
        'args' => array($this->path[2])));
      $msg = 'Sie sind jetzt angemeldet. Bitte ändern Sie Ihr Kennwort.';
    }
    
    if ($_SESSION['user']) {
      $cv = $cv_generator->model();
      $cv->url = $_SESSION['user']->url;
      $cv->save(array('code' => NULL, 'last' => time()));
      if (!isset($_SESSION['message'])) {
        $_SESSION['message'] = $msg;
      }
      goto('http://' . $_SESSION['user']->url . '.' . $config['mainhost'] . '/');
    }
    else {
      $_SESSION['message'] = 'Die Anmeldung schlug leider fehl.';
      goto('#account');
    }
  }
  
  /**
   * Action
   */
  function logout() {
    global $config;
    
    unset($_SESSION['user']);
    goto('http://' . $config['mainhost'] . '/');
  }
  
  /**
   * Action
   */
  function password() {
    if (!isset($_POST['email'])) {
      $_SESSION['message'] = 'Wir konnten Ihre E-Mail-Adresse nicht finden.';
      goto('/#account');
    }

    $cv_generator = load('cv');
    $user = $cv_generator->one(array(
      'where' => 'email = %s', 
      'args' => array($_POST['email'])));

    $cv = new cv;
    if ($user) {
      $i = 0;
      do {
        $i++;
        $code = base_convert(rand(), 10, 36);
        $cv->url = $user->url;
        if ($cv->save(array('code' => $code))) {
          send_mail($_POST['email'], '[cv8.me] Passwort verloren?', "Hallo,
          
über den folgenden Link können Sie sich anmelden:

http://{$_SERVER['HTTP_HOST']}/cv/login/{$code}
          
Viel Erfolg mit Ihrem Online-Lebenslauf!
Dr. Olav Schettler");
          $_SESSION['message'] = 'Wir haben Ihnen gerade eine E-Mail geschickt.';
          break;
        }
      }
      while ($i < 100);
    }
    else {
      $_SESSION['message'] = 'Wir konnten Ihre E-Mail-Adresse nicht finden.';
    }
    goto('#account');
  }

  /**
   * Action
   */
  function register() {
    global $config;
    
    $cv_generator = load('cv');

    if ($_POST) {
      $message = array();
      foreach (array(
        'email' => 'E-Mail', 
        'password' => 'Kennwort', 
        'password2' => 'Kennwort (nochmal)', 
        'url' => 'URL') as $field => $title) {
        if (!$_POST[$field]) {
          $message[] = 'Bitte Feld ' . $title . ' ausfüllen.';
        }
      }
      if ($_POST['email'] && !preg_match('#^[-+_\.\w]+@\w[-_\.\w]+$#', $_POST['email'])) {
        $message[] = 'Bitte eine gültige E-Mail-Adresse angeben.';
      }
      if ($_POST['password'] && $_POST['password'] != $_POST['password2']) {
        $message[] = 'Die Kennworte sind ungleich.';
      }
      if ($_POST['url'] && !preg_match('/^[-\w]+$/', $_POST['url'])) {
        $message[] = 'Die URL darf nur Buchstaben, Zahlen und die Zeichen -_ enthalten.';
      }
      if ($_POST['url'] && $cv_generator->one(array(
        'where' => 'url = %s', 
        'args' => array($_POST['url'])))) {

        $message[] = 'Die angegebene URL wird schon benutzt.';
      }
      if ($_POST['email'] && $cv_generator->one(array(
        'where' => 'email = %s', 
        'args' => array($_POST['email'])))) {
          
        $message[] = 'Die angegebene E-Mail ist schon registriert.';
      }

      if ($message) {
        $_SESSION['message'] = join('<br/>', $message);
        $_SESSION['data']['url'] = $_POST['url'];
        $_SESSION['data']['email'] = $_POST['email'];
        goto('#register');
      }
      
      $_POST['publicity'] = 'protected';
      $_POST['prot_passwd'] = gen_password();
      
      $cv = new cv;
      if (($result = $cv->save($_POST)) !== FALSE) {
        $dir = 'files/' . $_POST['url'];
        @mkdir($dir, 0755);

        $_SESSION['message'] = "Ihre Registrierung war erfolgreich.<br/>Ihr Lebenslauf ist kennwortgeschützt. Das Kennwort ist \"{$_POST['prot_passwd']}\".<br/>Unter \"Einstellungen\" können Sie dies ändern.";
        
        send_mail($_POST['email'], "[cv8] Herzlich willkommen", "Willkommen bei cv8.me.
          
Ihr Lebenslauf ist unter http://{$_POST['url']}.{$config['mainhost']} abgelegt.

Augenblicklich ist Ihr Lebenslauf nur nach Eingabe 
des Kennwortes \"{$_POST['prot_passwd']}\" zugänglich.

Sie können dies unter \"Einstellungen\" ändern.

Viel Erfolg mit Ihrem Online-Lebenslauf!
Dr. Olav Schettler");
        
        $this->login();
      }
      else {
        $_SESSION['message'] = 'Registrierung fehlgeschlagen.' . serialize($result);
        goto('#register');
      }
    }
  }
  
  /**
   * Action
   */
  function upload() {
    $this->layout = 'iframe';
    
    if ($_FILES) {
      if (!isset($_SESSION['user'])) {
        return;
      }
      list($major, $minor) = split('/', $_FILES['foto']['type']);
      error_log("TYPE $major, $minor");
      if ($major != 'image') {
        $_SESSION['messáge'] = 'Bitte laden Sie nur Bilder hoch.';
        return;
      }

      $dir = 'files/' . $_SESSION['user']->url;
      $fname = $dir . '/foto.' . $minor;
      if (move_uploaded_file($_FILES['foto']['tmp_name'], $fname)) {
        $this->fname = $fname;
        $this->fsize = getimagesize($fname);

        $cv_generator = load('cv');
        if ($this->data = $cv_generator->read($_SESSION['user']->url)) {
          $this->data->save(array('foto' => 'foto.' . $minor));
        }
        
        // remove derivatives
        foreach (glob($dir . '/*.foto.' . $minor) as $file) {
          unlink($file);
        }
      }
    }
  }
  
  /**
   * Action: Add a slot
   */
  function add() {
    //error_log("ADD.cv");
    $this->rendered = TRUE;
    $this->layout = FALSE;

    if (!isset($_SESSION['user']) || !$_SESSION['user']->url) {
      return '';
    }
    $this->data = $_SESSION['user'];
    $url = $_SESSION['user']->url;
    
    if ($this->args && $this->args[1]) {
      $section = $this->args[1];
    }
    error_log($section);
    if (!isset($_SESSION['user']->_has_many[$section]) || !isset($section)) {
      return '';
    }

    $slot_generator = load('slot');
    $seq = $slot_generator->find(array(
      'fields' => array('MAX(seq) AS sx'),
      'where' => 'url = %s AND section = %s',
      'args' => array($url, $section)));
     
    $max = $seq[0]['sx'];
    
    $item = array(
      'title' => 'Neuer Eintrag',
      'url' => $url,
      'section' => $section,
      'seq' => $max + 1,
      'enabled' => 1);
    
    error_log("SAVE: " . $item['id'] = $slot_generator->model()->save($item));
      
    return $this->_harp_entry($section, $item, array('class' => 'save harp'));
  }
  
  /**
   * Action
   */
  function show_slot() {
    $this->rendered = TRUE;
    $this->layout = FALSE;

    if (!isset($_SESSION['user']) || !$_SESSION['user']->url) {
      return '';
    }
    $this->data = $_SESSION['user'];
    $url = $_SESSION['user']->url;

    if ($this->args && count($this->args > 1)) {
      $section = $this->args[1];
      $id = $this->args[2];
    }
    if (   !isset($_SESSION['user']->_has_many[$section]) 
        || !isset($section) || !isset($id)) {
      return '';
    }

    $slot_generator = load('slot');
    $item = $slot_generator->one(array(
      'where' => 'id = %d', 
      'args' => array($id)));
    //D error_log("SHOW_SLOT.cv section=$section, id=$id => " . serialize($item));

    return $this->_harp_form($section, (array)$item, array('class' => 'save harp'));
  }

  /**
   * Action
   */
  function sort_slots() {
    $this->rendered = TRUE;
    $this->layout = FALSE;

    //D error_log(serialize($_POST));
    return '';
  }
  
  /**
   * Action: Called via AJAX
   */
  function harp() {
    $this->layout = FALSE;
    if (!isset($_SESSION['user']) || !$_SESSION['user']->url) {
      return '';
    }
    $this->data = $_SESSION['user'];
    $url = $_SESSION['user']->url;

    if ($this->args && count($this->args > 2)) {
      $this->section = $this->args[1];
    }
    if (   !isset($_SESSION['user']->_has_many[$this->section]) 
        || !isset($this->section)) {
      return '';
    }
    
    $cv_generator = load('cv');
    $this->data = $cv_generator->read($_SESSION['user']->url);
    $this->data->has_many($this->section);
  }
  
  /**
   * Helper
   */
  function _styling() {
    $cv =& $this->data;
    
    if ($cv->styling < 0) {
      $styles = array('erde', 'luft', 'wasser', 'feuer');
      $style = 'styles/' . $styles[$cv->styling + 4] . '/style.css';
    }
    else {
      $style = $cv->url . '/style.css';
    }
    if (isset($style) && file_exists($style)) {
      $this->stylesheet = $style;
    }
    else {
      $this->stylesheet = 'styles/erde/style.css';
    }
  }
}
